#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include "seqiot.h"
#include "model.h"
#include "sqlite.h"
#include "channel.h"
#include "redis.h"
#include "../iec60870/apdu.h"

static void _iec103_apdu_handle(void *ptr, channel_t *channel, device_t *device) {
    apdu_t *apdu = (apdu_t *) ptr;
}

int main(int argc, char *argv[]) {
    int i;

    if (argc <= 1) {
        fprintf(stderr, "usage: %s -i iec103_channel\n", argv[0]);
        return EXIT_FAILURE;
    }

    if (!redis_open()) {
        return EXIT_FAILURE;
    }

    obj_id channel_id = 0;
    for (i = 0; i < argc; ++i) {
        if (!strcasecmp("-i", argv[i])) {
            channel_id = atoi(argv[++i]);
        }
    }

    seqiot_t *seqiot = seqiot_new();
    read_config(seqiot, NULL, channel_id, -1);

    channel_t *channel = NULL;
    for (i = 0; i < seqiot->channels.size; ++i) {
        channel_t *curr = vector_get(&seqiot->channels, i);
        if (curr->super.id == channel_id) {
            if (cp_iec103 == curr->protocol) {
                channel = curr;
            } else {
                fprintf(stderr, "invalid protocol data_type %d.\n", curr->protocol);
            }

            break;
        }
    }

    if (NULL == channel) {
        fprintf(stderr, "channel %d not exists, please check your configuration.\n", channel_id);
        return EXIT_FAILURE;
    }

    if (-1 == channel_open_serial(channel)) {
        return EXIT_FAILURE;
    }

    char topic[64];
//	sprintf(topic, "sub.c%d.d%d");
    redis_subscribe(topic);

    signal(SIGINT, _signal_handler);
    signal(SIGTERM, _signal_handler);
    sched_iec60870(channel, seqiot, _iec103_apdu_handle);

    redis_close();
    channel_close(channel);
    free(seqiot);

    return EXIT_SUCCESS;
}
